package cn.iocoder.yudao.module.system.controller.admin.erp.warehouse;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.erp.warehouse.vo.WarehousePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.erp.warehouse.vo.WarehouseRespVO;
import cn.iocoder.yudao.module.system.controller.admin.erp.warehouse.vo.WarehouseSaveReqVO;
import cn.iocoder.yudao.module.system.core.ErpOperationField;
import cn.iocoder.yudao.module.system.core.ErpOperationLog;
import cn.iocoder.yudao.module.system.dal.dataobject.erp.warehouse.WarehouseDO;
import cn.iocoder.yudao.module.system.service.erp.operatelog.ErpOperateLogService;
import cn.iocoder.yudao.module.system.service.erp.warehouse.WarehouseService;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exceptionErr;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 仓库管理")
@RestController
@RequestMapping("/erp/warehouse")
@Validated
public class WarehouseController {

    @Resource
    private WarehouseService warehouseService;
    @Resource
    private ErpOperateLogService erpOperateLogService;
    @PostMapping("/create")
    @Operation(summary = "创建仓库管理")
    @ErpOperationLog(module = "仓库管理",description = "创建仓库")
    @PreAuthorize("@ss.hasPermission('erp:warehouse:create')")
    public CommonResult<Long> createWarehouse(@Valid @RequestBody WarehouseSaveReqVO createReqVO) throws NoSuchMethodException {
        String name = createReqVO.getName();
        if(StrUtil.isBlank(name)){
            throw exceptionErr(500,"仓库名不能为空");
        }
        WarehouseDO warehouseDO = warehouseService.byNameGetWarehouse(name);
        if(ObjectUtil.isNotNull(warehouseDO)){
            throw exceptionErr(500,"仓库名已被使用");
        }
        Long warehouseId = warehouseService.createWarehouse(createReqVO);
        WarehouseRespVO respVO = BeanUtils.toBean(warehouseService.getWarehouse(warehouseId), WarehouseRespVO.class);
        String content=" "+Arrays.stream(respVO.getClass().getDeclaredFields()).filter(field->ObjectUtil.isNotNull(field.getAnnotation(ErpOperationField.class))
        ).map(field -> {field.setAccessible(true);try{
        return field.getAnnotation(ErpOperationField.class).name() + ":" + field.get(respVO);
        } catch (IllegalAccessException e) {throw new RuntimeException(e);}
        }).collect(Collectors.joining(","));
        erpOperateLogService.createOperateLog(SecurityFrameworkUtils.getLoginUserId(),content,getClass().getDeclaredMethod("createWarehouse",WarehouseSaveReqVO.class));
        return success(warehouseId);
    }

    @PutMapping("/update")
    @Operation(summary = "更新仓库管理")
    @ErpOperationLog(module = "仓库管理",description = "更新仓库")
    @PreAuthorize("@ss.hasPermission('erp:warehouse:update')")
    public CommonResult<Boolean> updateWarehouse(@Valid @RequestBody WarehouseSaveReqVO updateReqVO) throws NoSuchMethodException {
        String name = updateReqVO.getName();
        if(StrUtil.isBlank(name)){
            throw exceptionErr(500,"仓库名不能为空");
        }
        WarehouseDO warehouseDO = warehouseService.byNameGetWarehouse(name);
        if(ObjectUtil.isNotNull(warehouseDO)&&!ObjectUtil.equal(warehouseDO.getId(),updateReqVO.getId())){
            throw exceptionErr(500,"仓库名已被使用");
        }
        WarehouseRespVO oldItem = BeanUtils.toBean(warehouseService.getWarehouse(updateReqVO.getId()),WarehouseRespVO.class);
        warehouseService.updateWarehouse(updateReqVO);
        WarehouseRespVO newItem =BeanUtils.toBean(warehouseService.getWarehouse(updateReqVO.getId()),WarehouseRespVO.class);
        String oldContent=" 原来数据 "+Arrays.stream(oldItem.getClass().getDeclaredFields()).filter(field->ObjectUtil.isNotNull(field.getAnnotation(ErpOperationField.class))
        ).map(field -> {field.setAccessible(true);try{return field.getAnnotation(ErpOperationField.class).name() + ":" + field.get(oldItem);
        } catch (IllegalAccessException e) {throw new RuntimeException(e);}
        }).collect(Collectors.joining(","));
        String newContent=";修改完数据 "+Arrays.stream(newItem.getClass().getDeclaredFields()).filter(field->ObjectUtil.isNotNull(field.getAnnotation(ErpOperationField.class))
        ).map(field -> {field.setAccessible(true);try{return field.getAnnotation(ErpOperationField.class).name() + ":" + field.get(newItem);
        } catch (IllegalAccessException e) {throw new RuntimeException(e);}
        }).collect(Collectors.joining(","));
        String content=oldContent.concat(newContent);
        erpOperateLogService.createOperateLog(SecurityFrameworkUtils.getLoginUserId(),content,getClass().getDeclaredMethod("updateWarehouse",WarehouseSaveReqVO.class));

        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除仓库管理")
    @Parameter(name = "id", description = "编号", required = true)
    @ErpOperationLog(module = "仓库管理",description = "删除仓库")
    @PreAuthorize("@ss.hasPermission('erp:warehouse:delete')")
    public CommonResult<Boolean> deleteWarehouse(@RequestParam("id") Long id) throws NoSuchMethodException {
        WarehouseDO warehouse = warehouseService.getWarehouse(id);
        warehouseService.deleteWarehouse(id);
        String content=":"+warehouse.getName();
        erpOperateLogService.createOperateLog(SecurityFrameworkUtils.getLoginUserId(),content,getClass().getDeclaredMethod("deleteWarehouse",Long.class));
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得仓库管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:warehouse:query')")
    public CommonResult<WarehouseRespVO> getWarehouse(@RequestParam("id") Long id) {
        WarehouseDO warehouse = warehouseService.getWarehouse(id);
        return success(BeanUtils.toBean(warehouse, WarehouseRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得仓库管理分页")
    @PreAuthorize("@ss.hasPermission('erp:warehouse:query')")
    public CommonResult<PageResult<WarehouseRespVO>> getWarehousePage(@Valid WarehousePageReqVO pageReqVO) {
        PageResult<WarehouseDO> pageResult = warehouseService.getWarehousePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, WarehouseRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出仓库管理 Excel")
    @PreAuthorize("@ss.hasPermission('erp:warehouse:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportWarehouseExcel(@Valid WarehousePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<WarehouseDO> list = warehouseService.getWarehousePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "仓库管理.xls", "数据", WarehouseRespVO.class,
                        BeanUtils.toBean(list, WarehouseRespVO.class));
    }


    @PostMapping("/batch-delete")
    @Operation(summary = "删除仓库管理")
    @ErpOperationLog(module = "仓库管理",description = "删除仓库")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:warehouse:delete')")
    public CommonResult<Boolean> batchDeleteWarehouse(@RequestBody List<Long>ids) throws NoSuchMethodException {
        String names=warehouseService.getWarehouses(ids).stream().map(WarehouseDO::getName).collect(Collectors.joining(","));
        ids.forEach(id->warehouseService.deleteWarehouse(id));
        String content=":"+names;
        erpOperateLogService.createOperateLog(SecurityFrameworkUtils.getLoginUserId(),content,getClass().getDeclaredMethod("deleteWarehouse",Long.class));

        return success(true);
    }
}